import React, {Component} from 'react'
import StyleUtils from "../../../res/styles/StyleUtils";
import ScrollableTabView from 'react-native-scrollable-tab-view';
import MyBusinessPage from "./MyBusinessPage";
import MatrixPlanPage from "./MatrixPlanPage";
import {DeviceEventEmitter, Image, StyleSheet, Text, TouchableOpacity, View} from "react-native";
import I18n from "../../../res/language/i18n";
import IparNetwork, {SERVER_TYPE} from "../../../httpUtils/IparNetwork";
import CommonUtils from "../../../common/CommonUtils";
import MyGeneralBusinessPage from "./MyGeneralBusinessPage";
import U_2ProgramPage from "./U_2ProgramPage";
import {DATE_DATA} from "../../../res/json/monthsJson";

let tabBarData = [
    {name: '', rank: 2, is_open: false, image: require('../../../res/images/planIcon/ic_rocket.png')},
    {name: '', rank: 3, is_open: false, image: require('../../../res/images/planIcon/ic_rocket.png')},
    {name: '', rank: 4, is_open: false, image: require('../../../res/images/planIcon/ic_grow.png')},
    {name: '', rank: 5, is_open: false, image: require('../../../res/images/planIcon/ic_matrix.png')},
    {name: '', rank: 6, is_open: false, image: require('../../../res/images/planIcon/ic_yutu.png')},
    {name: '', rank: 7, is_open: false, image: require('../../../res/images/planIcon/ic_rocket.png')},
    {name: '', rank: 8, is_open: false, image: require('../../../res/images/planIcon/ic_rocket.png')},
    {name: '', rank: 9, is_open: false, image: require('../../../res/images/planIcon/ic_yutu.png')},
];

export default class PlansMainPage extends Component {

    constructor(props) {
        super(props);

        this.iparNetwork = new IparNetwork();

        this.country = '';
        this.isLoadingPlan = true;
        this.isLoadingSubAccount = true;

        this.state = {
            plansData: [],//用户参加的计划
            isRankTow: false,
            isRankThree: false,
            isRankFour: false,
            isRankFive: false,
            isRankSex: false,
            towPageTitle: '',
            threePageTitle: '',
            fourPageTitle: '',
            fivePageTitle: '',
            sexPageTitle: '',

            userData: null,
            usersData: null,

            rankTowUser: null,//子账号
            rankThreeUser: null,//子账号
            rankFourUser: null,//子账号
            rankSevenUser: null,//子账号

            subAccountMatrix: [],//matrix plan 的数据
            subAccountU_2: [],//U_2 plan 的数据
            subAccountInternation: [],//8 plan 的数据

            rewardStatistics: null,


        }
    }

    componentDidMount() {


        CommonUtils.getAcyncInfo('userInfo')
            .then((result) => {
                let parse = JSON.parse(result);

                this.country = parse.country;
                this.onLoadPlansDdata();

                this.getSubAccount(parse.main_user_id);//获取子账号

                this.getRewardStatistics(parse.user_id, parse.main_user_id);//获取奖金


                let openPlan = parse.open_plan;

                let _userPlans = [];
                if (openPlan) {
                    for (let i = 0, len = tabBarData.length; i < len; i++) {
                        let tabBarDatum = tabBarData[i];
                        if (openPlan.indexOf(tabBarDatum.rank + '') !== -1) {
                            tabBarDatum.is_open = true;
                            _userPlans.push(tabBarDatum);
                        }
                    }
                }

                this.setState({
                    plansData: _userPlans,
                    userData: parse,
                });


            });

    }


    /**
     * 获取摸个用户的子账号
     */
    getSubAccount(userId) {
        CommonUtils.showLoading();

        this.iparNetwork.getRequest(SERVER_TYPE.admin + 'getSubAccount?', 'main_user_id=' + userId)
            .then((result) => {
                if (result.code === 200) {
                    let data = result.data;

                    let _rankTowUser = null;
                    let _rankThreeUser = null;
                    let _rankFourUser = null;
                    let _rankSevenUser = null;
                    let _rank9User = null;
                    let _subAccountMatrix = [];
                    let _subAccountU_2 = [];
                    let _subAccountInternation = [];
                    for (let i = 0, len = data.length; i < len; i++) {
                        let datum = data[i];
                        switch (datum.rank) {
                            case 2:
                                _rankTowUser = datum;
                                break;
                            case 3:
                                _rankThreeUser = datum;
                                break;
                            case 4:
                                _rankFourUser = datum;
                                break;
                            case 5:
                                _subAccountMatrix.push(datum);
                                break;
                            case 6:
                                _subAccountU_2.push(datum);
                                break;
                            case 7:
                                _rankSevenUser = datum;
                                break;
                            case 8:
                                _subAccountInternation.push(datum);
                                break;
                            case 9:
                                _rank9User = datum;
                                break;
                        }
                    }


                    this.isLoadingSubAccount = false;
                    if (!this.isLoadingPlan ? false : this.state.isLoading) {
                        CommonUtils.showLoading();
                    } else {
                        CommonUtils.dismissLoading();
                    }

                    this.setState({
                        subAccountMatrix: _subAccountMatrix,
                        subAccountU_2: _subAccountU_2,
                        subAccountInternation: _subAccountInternation,
                        usersData: data,
                        rankTowUser: _rankTowUser,
                        rankThreeUser: _rankThreeUser,
                        rankFourUser: _rankFourUser,
                        rankSevenUser: _rankSevenUser,
                        rank9User: _rank9User,
                    })

                } else {
                    this.isLoadingSubAccount = false;
                    if (!this.isLoadingPlan) {
                        CommonUtils.dismissLoading();

                    }
                }

            })
            .catch((error) => {
                this.isLoadingSubAccount = false;
                if (!this.isLoadingPlan) {
                    CommonUtils.dismissLoading();

                }
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log('PlansMainPage-----getSubAccount--error: ', error);
            })
    }


    /**
     * 获取奖金
     */
    getRewardStatistics(user_id, main_user_id) {

        /**
         * 暂时注释
         */
        let _time = DATE_DATA.year + '-' + (DATE_DATA.month);
        // if (parseInt(DATE_DATA.day) < 15) {
        //     _time = DATE_DATA.year + '-' + (getFormatDate(DATE_DATA.month - 1));
        // }
        this.iparNetwork.getRequest(SERVER_TYPE.admin + 'getRewardStatistics?', 'main_user_id=' + main_user_id + '&time=' + _time)
            .then((result) => {
                if (result.code === 200) {
                    this.setState({
                        rewardStatistics: result.data,
                    })
                }
            })
            .catch((error) => {
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log('PlansMainPage-----getRewardStatistics--error: ', error);
            })

    }


    /**
     * 获取奖励计划信息
     */
    onLoadPlansDdata() {
        CommonUtils.showLoading();


        this.iparNetwork.getRequest(SERVER_TYPE.admin + 'getRank?', 'country=' + this.country)
            .then((result) => {
                if (result.code === 200) {
                    for (let i = 0, len = result.data.length; i < len; i++) {
                        let datum = result.data[i];
                        let tabBarDatum = tabBarData[datum.rank - 2];

                        if (tabBarDatum)
                            tabBarDatum.name = datum.rank_name;
                    }
                    this.isLoadingPlan = false;
                    if (!this.isLoadingSubAccount) {
                        CommonUtils.dismissLoading();
                    }
                } else {
                    this.isLoadingPlan = false;
                    if (!this.isLoadingSubAccount) {
                        CommonUtils.dismissLoading();

                    }
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
                }
            })
            .catch((error) => {
                this.isLoadingPlan = false;
                if (!this.isLoadingSubAccount) {
                    CommonUtils.dismissLoading();
                }
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log('PlansMainPage---onLoadPlansDdata--error-', error)
            })
    }


    render() {

        let state = this.state;

        return <View style={[StyleUtils.flex]}>


            <ScrollableTabView
                ref={'ScrollableTabView'}
                locked={true}
                scrollWithoutAnimation={true}
                tabBarPosition='bottom'
                renderTabBar={() => <RenderTabBar plansData={this.state.plansData} {...this.props}/>}>

                <MyGeneralBusinessPage
                    rewardStatisticsData={state.rewardStatistics}
                    usersData={state.usersData}
                    userData={state.userData}
                    plansData={this.state.plansData}
                    gotoPage={(index) => this.refs.ScrollableTabView.goToPage(index)}
                    {...this.props}/>

                {tabBarData[0].is_open && // rank = 2
                <MyBusinessPage
                    userData={state.rankTowUser}
                    rewardStatisticsData={state.rewardStatistics}
                    rank={2}
                    title={tabBarData[0].name} {...this.props}/>}
                {tabBarData[1].is_open &&//rank = 3
                <MyBusinessPage
                    userData={state.rankThreeUser}
                    rewardStatisticsData={state.rewardStatistics}
                    rank={3}
                    title={tabBarData[1].name} {...this.props}/>}
                {tabBarData[2].is_open &&//grow 4
                <MyBusinessPage
                    userData={state.rankFourUser}
                    rewardStatisticsData={state.rewardStatistics}
                    rank={4}
                    title={tabBarData[2].name} {...this.props}/>}


                {tabBarData[3].is_open && //5
                <MatrixPlanPage
                    rewardStatisticsData={state.rewardStatistics}
                    MatrixPlanData={state.subAccountMatrix}
                    userData={state.userData}
                    title={tabBarData[3].name}
                    {...this.props}/>}

                {tabBarData[4].is_open &&
                <U_2ProgramPage // 6
                    rewardStatisticsData={state.rewardStatistics}
                    userData={state.userData}
                    U_2ProgramData={state.subAccountU_2}
                    title={tabBarData[4].name}
                    rank={6}
                    {...this.props}/>}

                {tabBarData[5].is_open &&//new grow / 7
                <MyBusinessPage
                    userData={state.rankSevenUser}
                    rewardStatisticsData={state.rewardStatistics}
                    rank={7}
                    title={tabBarData[5].name} {...this.props}/>}

                {tabBarData[6].is_open &&
                <U_2ProgramPage // 8
                    rewardStatisticsData={state.rewardStatistics}
                    userData={state.userData}
                    U_2ProgramData={state.subAccountInternation}
                    title={tabBarData[6].name}
                    rank={8}
                    {...this.props}/>}

                {tabBarData[7].is_open &&
                <MyBusinessPage
                    userData={state.rank9User}
                    rewardStatisticsData={state.rewardStatistics}
                    rank={9}
                    title={tabBarData[7].name} {...this.props}/>}


            </ScrollableTabView>


        </View>
    }

}

class RenderTabBar extends Component {


    onItemClick(index) {
        this.props.goToPage(index)
    }


    render() {


        let plansData = this.props.plansData;


        let tintStyle = this.props.activeTab !== 0 ? '#cdcdcd' : '#000000';

        return <View style={plansData && plansData.length > 0 ? styles.tabs : null}>


            {plansData.length > 0 ? <TouchableOpacity
                onPress={() => {
                    this.onItemClick(0)
                }}
                style={[{flex: 1}, StyleUtils.center]}>

                <Image
                    style={[StyleUtils.tabIconSize, {tintColor: tintStyle}]}
                    source={require('../../../res/images/planIcon/ic_plan_home.png')}/>
                <Text
                    numberOfLines={2}
                    style={[styles.tabText, {color: tintStyle}, StyleUtils.smallFont]}>{I18n.t('default.myBusiness')} </Text>

            </TouchableOpacity> : null}

            {plansData && plansData.length > 0 ? plansData.map((item, i) => {
                let tintStyle = this.props.activeTab !== i + 1 ? '#cdcdcd' : '#000000';
                let rowData = tabBarData[plansData[i].rank - 2];
                return <TouchableOpacity
                    key={i}
                    onPress={() => {
                        this.onItemClick(i + 1)
                    }}
                    style={[{flex: 1}, StyleUtils.center]}>

                    <Image
                        style={[StyleUtils.tabIconSize, {tintColor: tintStyle}]}
                        source={rowData.image}/>
                    <Text
                        numberOfLines={2}
                        style={[styles.tabText, {color: tintStyle}, StyleUtils.smallFont]}>{rowData.name}</Text>

                </TouchableOpacity>
            }) : null}


        </View>
    }


}

const styles = StyleSheet.create({
    tabs: {
        flexDirection: 'row',
        height: 58,
        backgroundColor: 'white',
    },

    tabText: {fontSize: 10, height: 24, textAlign: 'center'},
});